package com.hhkj.open.api.service.biz.impl;

import cn.hutool.core.util.ObjectUtil;
import com.hhkj.admin.student.common.utils.StudentUtils;
import com.hhkj.admin.student.domain.Student;
import com.hhkj.admin.student.service.base.StudentService;
import com.hhkj.admin.student.service.extend.StudentExtendService;
import com.hhkj.api.student.service.biz.ApiStudentBizService;
import com.hhkj.open.api.model.req.LoginReq;
import com.hhkj.open.api.service.biz.OpenApiStudentBizService;
import com.hhkj.open.sys.service.biz.OpenSysUserService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.hhkj.api.common.session.holder.model.LoginStudent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * OpenStudentBizServiceImpl
 *
 * @author HHKJ-SERVER-ZJ
 * @since 2023/7/13 8:43
 */
@Service
public class OpenApiStudentBizServiceImpl implements OpenApiStudentBizService
{
    @Autowired
    private ApiStudentBizService apiStudentBizService;
    @Autowired
    private OpenSysUserService openSysUserService;
    @Autowired
    private StudentExtendService studentExtendService;
    @Autowired
    private StudentService studentService;

    @Override
    public LoginStudent login(LoginReq req)
    {
        // 获取机构信息
        SysUser entUser = openSysUserService.getEntUser(req);
        // 根据身份证获取学员信息
        Student studentPo = studentExtendService.getByIdCardAndCreateBy(req.getIdCard(), entUser.getUserId());
        if (ObjectUtil.isNull(studentPo)) {
            studentPo = this.createStudent(req, entUser);
        }
        return apiStudentBizService.doLogin(studentPo);
    }

    /**
     * 创建学员信息
     *
     * @param req     请求信息
     * @param insUser 机构用信息
     * @return 学员信息
     */
    private Student createStudent(LoginReq req, SysUser insUser)
    {
        Student studentDo = new Student();
        studentDo.setName(req.getNickName());
        studentDo.setIdCard(req.getIdCard());
        studentDo.setPhone(req.getContactPhone());
        StudentUtils.encryptPassword(studentDo);
        studentDo.setCreateBy(insUser.getUserId());
        studentDo.setOrigSysId(req.getOrigSysId());
        studentService.save(studentDo);
        return studentDo;
    }


}
